<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  
    <meta name="description" content="我在这里，一个死宅的个人自留地，一个基于hexo的个人博客。随便写写，分享生活，文笔不好，欢迎吐槽！">
  

  
    <meta name="keywords" content="我在这里 个人博客 自留地 死宅 hexo flex-block">
  

  
    <meta name="author" content="后来@">
  

  

  

  <title>使用marked解析markdown为html | 后来@&#39;s Blog</title>

  

  
    <link rel="icon" href="/favicon.ico">
  

  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
    <link href="https://cdn.bootcss.com/highlight.js/9.15.6/styles/monokai.min.css" rel="stylesheet">
  

  
<link rel="stylesheet" href="/css/style.css">

<meta name="generator" content="Hexo 4.2.0"></head>
<body>
  <div class="root-container">
    <!-- navbar -->
<nav class="navbar">
  <div class="navbar-content">
    <!-- logo -->
    <div class="navbar-logo">
      <a href="/">
        
          后来@&#39;s Blog
        
      </a>
    </div>
    <!-- link -->
    <div class="navbar-link">
      <div class="navbar-btn">
        <div></div>
        <div></div>
        <div></div>
      </div>
      <ul class="navbar-list">
        
          <li class="navbar-list-item"><a href="/">首页</a></li>
        
          <li class="navbar-list-item"><a href="/tags">标签</a></li>
        
          <li class="navbar-list-item"><a href="/links">友链</a></li>
        
          <li class="navbar-list-item"><a href="/messages">留言</a></li>
        
          <li class="navbar-list-item"><a href="/about">关于</a></li>
        
          <li class="navbar-list-item"><a href="/anime">アニメ</a></li>
        
      </ul>
    </div>
  </div>
</nav>

    
<!-- header container -->
<header class="header-container post">

  
  

  
  

  
  

  
  

  
  
    <div class="header-content">
      <div class="post-image" style="background-image: url(https://qiniu.miiiku.xyz/src/images/banner.jpg)"></div>
      <div class="post-text">
        <div class="type-wrap">
          <a class="article-category-link" href="/categories/%E7%AC%94%E8%AE%B0/">笔记</a>
        </div>
        <h1 class="title-wrap">使用marked解析markdown为html</h1>
        <h2 class="title-sub-wrap">
          <strong>后来@</strong>
          <span>发布于</span>
          
  <a href="javascript:;" class="article-date">
    <time datetime="2017-02-27T09:25:15.000Z" itemprop="datePublished">2017-02-27</time>
  </a>

        </h2>
      </div>
    </div>
  

  
  

  </header>

    <!-- 文章 -->

<!-- 文章内容 -->

<div class="body-container">
  <article class="content-container article-container">
    <div class="article-content">
      
      

      <div class="article-entry">
        <p>前段时间玩了会儿hexo，发现用markdown写博客真的很爽，语法也十分的简介。</p>
<p>于是打算将博客的富文本编辑器换成markdown。</p>
<p>我这里是使用的marked</p>
<blockquote>
<p>Markdown 是一种轻量级的「标记语言」，它的优点很多，目前也被越来越多的写作爱好者，撰稿者广泛使用。看到这里请不要被「标记」、「语言」所迷惑，Markdown 的语法十分简单。常用的标记符号也不超过十个，这种相对于更为复杂的 HTML 标记语言来说，Markdown 可谓是十分轻量的，学习成本也不需要太多，且一旦熟悉这种语法规则，会有一劳永逸的效果。</p>
</blockquote>
<hr>
<blockquote>
<p>marked 是一个 JavaScript 编写的全功能 Markdown 解析和编译器。<br>marked 的目的是快速的编译超大块的Markdown文本而不必担心结果会出乎意料或者花费很长时间。<br>marked 最初是为 Node.JS编写，现在已完全兼容客户端浏览器。<br>新版本号称速度比C语言写的Markdown转换工具Discount 还要快。</p>
</blockquote>
<h3 id="1-安装marked"><a href="#1-安装marked" class="headerlink" title="1.安装marked"></a>1.安装marked</h3><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">npm install marked --save<br></code></pre></td></tr></table></figure>
<h3 id="2-引用"><a href="#2-引用" class="headerlink" title="2.引用"></a>2.引用</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> marked = <span class="hljs-built_in">require</span>(<span class="hljs-string">'marked'</span>)<br></code></pre></td></tr></table></figure>
<h3 id="3-转换为html"><a href="#3-转换为html" class="headerlink" title="3.转换为html"></a>3.转换为html</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> html = marked(<span class="hljs-string">'### hello markdown'</span>) <span class="hljs-comment">// &lt;h3&gt;hello markdown&lt;/h3&gt;</span><br></code></pre></td></tr></table></figure>
<h3 id="一些参数说明"><a href="#一些参数说明" class="headerlink" title="一些参数说明"></a>一些参数说明</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> marked = <span class="hljs-built_in">require</span>(<span class="hljs-string">'marked'</span>);<br><br>marked.setOptions(&#123;<br>	<span class="hljs-attr">renderer</span>: <span class="hljs-keyword">new</span> marked.Renderer(),<br>	<span class="hljs-attr">gfm</span>: <span class="hljs-literal">true</span>,<br>	<span class="hljs-attr">tables</span>: <span class="hljs-literal">true</span>,<br>	<span class="hljs-attr">breaks</span>: <span class="hljs-literal">false</span>,<br>	<span class="hljs-attr">pedantic</span>: <span class="hljs-literal">false</span>,<br>	<span class="hljs-attr">sanitize</span>: <span class="hljs-literal">true</span>,<br>	<span class="hljs-attr">smartLists</span>: <span class="hljs-literal">true</span>,<br>	<span class="hljs-attr">smartypants</span>: <span class="hljs-literal">false</span><br>&#125;);<br><br><span class="hljs-built_in">console</span>.log(marked(<span class="hljs-string">'I am using __markdown__.'</span>));<br></code></pre></td></tr></table></figure>
<ul>
<li>-o, –output [output]: 指定输出文件，默认为当前控制台</li>
<li>-i, –input [input]: 指定输入文件或最后一个参数，默认为当前控制台输入</li>
<li>-t, –tokens: 输出token流代替HTML</li>
<li>–pedantic: 只解析符合markdown.pl定义的，不修正markdown的错误</li>
<li>–gfm: 启动Github样式的Markdown</li>
<li>–breaks: 支持Github换行符，必须打开gfm选项</li>
<li>–tables: 支持Github表格，必须打开gfm选项</li>
<li>–sanitize: 原始输出，忽略HTML标签</li>
<li>–smart-lists: 优化列表输出</li>
<li>–lang-prefix [prefix]: 设置前置样式</li>
<li>–no-etc: 选择的反正标识</li>
<li>–silent: 不输出错误信息</li>
<li>-h, –help: 帮助信息</li>
</ul>
<h3 id="4-marked防注入"><a href="#4-marked防注入" class="headerlink" title="4.marked防注入"></a>4.marked防注入</h3><p>如下MD被编译为HTML时，会执行script里的代码，弹出xss攻击<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">var</span> html = marked(<span class="hljs-string">'&lt;script&gt;alert("xss攻击")&lt;/script&gt;'</span>)<br></code></pre></td></tr></table></figure></p>
<p>设置<em>sanitize</em>为ture，即可过滤到script标签<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs js">marked.setOptions(&#123; <span class="hljs-attr">sanitize</span>: <span class="hljs-literal">true</span> &#125;)<br></code></pre></td></tr></table></figure></p>
<h3 id="5-自定义渲染"><a href="#5-自定义渲染" class="headerlink" title="5.自定义渲染"></a>5.自定义渲染</h3><p>自定义渲染选项允许你以自定义的方式渲染内容，并把之前的规则设置覆盖掉。</p>
<p>块级标签支持以下渲染：</p>
<ul>
<li>code(string code, string language)</li>
<li>blockquote(string quote)</li>
<li>html(string html)</li>
<li>heading(string text, number level)</li>
<li>hr()</li>
<li>list(string body, boolean ordered)</li>
<li>listitem(string text)</li>
<li>paragraph(string text)</li>
<li>table(string header, string body)</li>
<li>tablerow(string content)</li>
<li>tablecell(string content, object flags)</li>
</ul>
<p>行级标签支持以下渲染：</p>
<ul>
<li>strong(string text)</li>
<li>em(string text)</li>
<li>codespan(string code)</li>
<li>br()</li>
<li>del(string text)</li>
<li>link(string href, string title, string text)</li>
<li>image(string href, string title, string text)</li>
</ul>
<h4 id="举一个栗子🌰："><a href="#举一个栗子🌰：" class="headerlink" title="举一个栗子🌰："></a>举一个栗子🌰：</h4><p>默认的渲染a标签为当前窗口打开，如果我想让它新窗口打开，可以如下：</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs stylus"><span class="hljs-selector-tag">var</span> md = <span class="hljs-string">'[http://baidu.com](baidu.com "百度")'</span><br><br><span class="hljs-comment">// 默认的渲染结果</span><br><span class="hljs-selector-tag">var</span> <span class="hljs-selector-tag">a</span> = marked(a)<br><span class="hljs-comment">// 得到的a为&lt;a href="http://baidu.com" title="百度"&gt;baidu.com&lt;/a&gt;</span><br><br><span class="hljs-comment">// 添加自定义渲染</span><br><span class="hljs-selector-tag">var</span> rendererMD = new marked.Renderer()<br><br>rendererMD<span class="hljs-selector-class">.link</span> = function (href, title, text) &#123;<br>    return `&lt;<span class="hljs-selector-tag">a</span> href=<span class="hljs-string">"$&#123;href&#125;"</span> title=<span class="hljs-string">"$&#123;title || text&#125;"</span> target=<span class="hljs-string">"_blank"</span>&gt;$&#123;text&#125;&lt;/a&gt;`<br>&#125;<br><br>marked.setOptions(&#123; renderer: rendererMD &#125;)<br><br><span class="hljs-selector-tag">var</span> _blankA = marked(a)<br><span class="hljs-comment">// 得到的_blankA为&lt;a href="http://baidu.com" title="百度" target="_blank"&gt;baidu.com&lt;/a&gt;</span><br></code></pre></td></tr></table></figure>
<p>不声明renderer时，默认为<em>new Renderer()</em></p>
<h3 id="6-语法高亮"><a href="#6-语法高亮" class="headerlink" title="6.语法高亮"></a>6.语法高亮</h3><p>需要安装<em>highlight.js</em></p>
<figure class="highlight mipsasm"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mipsasm">npm <span class="hljs-keyword">install </span>highlight.<span class="hljs-keyword">js </span>--save<br></code></pre></td></tr></table></figure>
<p>设置语法高亮(为了正常显示，页面需要引入highlight.js的css)<br><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">const</span> highlight = <span class="hljs-built_in">require</span>(<span class="hljs-string">'highlight.js'</span>)<br><br>marked.setOptions(&#123;<br>    <span class="hljs-attr">highlight</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">code</span>) </span>&#123;<br>        <span class="hljs-keyword">return</span> highlight.highlightAuto(code).value<br>    &#125;<br>&#125;)<br></code></pre></td></tr></table></figure></p>
<p>以上！！！</p>

      </div>

      <div class="article-footer">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/html/" rel="tag">#html</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/markdown/" rel="tag">#markdown</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/marked/" rel="tag">#marked</a></li></ul>
      </div>

      <div class="article-navs">
        
<nav class="card-container card-article-nav">
  <div class="card-wrap">
    
      <div id="article-nav-newer" class="card-item">
        <article>
          
          <a class="card-link article-nav-link" href="/2017/02/281034.html"></a>
          <strong class="article-nav-caption">Newer</strong>
          <p class="article-nav-title">
            
              局部安装webpack提示拒绝安装本身的依赖
            
          </p>
        </article>
      </div>
    
    
      <div id="article-nav-older" class="card-item">
        <article>
          
          <a class="card-link article-nav-link" href="/2017/01/241725.html"></a>
          <strong class="article-nav-caption">Older</strong>
          <p class="article-nav-title">
            
              HTML中的Meta标签
            
          </p>
        </article>
      </div>
    
  </div>
</nav>

      </div>
      
      

  
  <div class="valine-container">
    <div id="valine_thread" class="valine-thread"></div>
  </div>

  
  
  <div class="disqus-container">
    <p id="disqus_error" class="disqus-error" style="display: none;">如果你看不到评论，那么就真的看不到评论 w(゜Д゜)w</p>
    <div id="disqus_thread" class="disqus-thread"></div>
  </div>
  


    </div>
  </article>
</div>

    <!-- footer container -->
<footer id="footer" class="footer">
  <div class="footer-container">
    <p>&copy; 2020 <a href="/" target="_blank">后来@</a></p>

    <style>
      .colour-text {
        display: inline-block;
        margin: 20px auto;
        text-align: left;
        background-image: linear-gradient(to right, deeppink, pink, hotpink, lightpink, deeppink);
        -webkit-text-fill-color: transparent;
        -webkit-background-clip: text;
      }
    </style>
    
    <p class="colour-text">
      “关于泉前辈，我可以和他约会吗？” “不可以”
    </p>

    

    
      <p><a href="http://www.miitbeian.gov.cn" target="_blank">蜀ICP备15014309号</a></p>
    

    <p>Powered by <a href="https://hexo.io" target="_blank">Hexo</a> Theme - <a href="https://github.com/miiiku/flex-block" target="_blank">flex-block</a></p>
  </div>
</footer>
  </div>

  
  

  <!-- disqus 评论 start -->
  <script type="text/javascript">
    /*
     *  RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS.
     *  LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables
     */
    
    /*
      var disqus_config = function () {
        this.page.url = PAGE_URL;  // Replace PAGE_URL with your page's canonical URL variable
        this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
      };
    */

    (function() {
      var d = document, s = d.createElement('script'), c = d.querySelector(".disqus-container");
      if (!c) return;
      s.src = 'https://sukoshi95.disqus.com/embed.js';
      s.setAttribute('data-timestamp', +new Date());
      s.onerror = () => {
        let t = document.querySelector("#disqus_error");
        t.style.display = "block";
      }
      (d.head || d.body).appendChild(s);
    })();
  </script>
  <!-- disqus 评论 end -->
  

  <!-- aplayer 音频 start -->
  
<link rel="stylesheet" href="/lib/APlayer.min.css">

  
<script src="/lib/APlayer.min.js"></script>

  <script type="text/javascript">
    const aplayer = document.querySelectorAll(".aplayer");
    aplayer && initaplayer(aplayer);
    function initaplayer(els) {
      let elsArr = Array.from(els);
      elsArr.forEach(el => {
        new APlayer({
          container: el,
          audio: { ...el.dataset },
          theme: "#b7daff",
          lrcType: 3,
          autoplay: false,
          loop: false,
          mutex: true,
        });
      });
    }
  </script>
  <!-- aplayer 音频 end -->
  

<!-- dplayer 视频 start -->

<link rel="stylesheet" href="/lib/DPlayer.min.css">


<script src="/lib/DPlayer.min.js"></script>

<script type="text/javascript">
  const dplayer = document.querySelectorAll(".dplayer");
  dplayer && initDPlayer(dplayer);
  function initDPlayer(els) {
    let elsArr = Array.from(els);
    elsArr.forEach(el => {
      let url = el.dataset.url;
      let cover = el.dataset.cover;
      new DPlayer({
        container: el,
        video: { url: url, pic: cover },
        theme: "#b7daff",
        autoplay: false,
        loop: false,
        mutex: true,
      });
    });
  }
</script>
<!-- dplayer 视频 end -->


<!-- waterfall 瀑布流 start -->

<script src="/lib/waterfall.min.js"></script>

<script type="text/javascript">

const waterfalls = document.querySelectorAll(".waterfall-container");

if (waterfalls && waterfalls.length > 0) {
  waterfalls.forEach((waterfall, index) => {
    let cls = "waterfall-container-" + index;
    waterfall.classList.add(cls);
    initWaterfall(cls, waterfall);
  });
}

function initWaterfall(selector, el) {
  const options = {};
  if (Object.keys(el.dataset).length > 0) {
    for (let k in el.dataset) {
      options[k] = el.dataset[k];
    }
  }
  waterfall(`.${selector}`, options);
}
</script>
<!-- waterfall 瀑布流 end -->


  <!-- zoom start -->
  
<script src="/lib/zoom.min.js"></script>

  <script type="text/javascript">
    document.querySelector(".article-content") && zoom(".article-content");
  </script>
  <!-- zoom end -->
  



  


  


  <!-- Baidu Analytics START -->
  <script>
    var _hmt = _hmt || [];
    (function () {
      if (window.location.hostname === "localhost" || window.location.hostname.startsWith("192.168")) {
        return console.log("本地调试");
      }
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?410f4beade12e8df64ea4c5622313220";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>
  <!-- Baidu Analytics End -->

  


  <!-- Tencent Analytics START -->
  <script>
    (function() {
      if (window.location.hostname === "localhost" || window.location.hostname.startsWith("192.168")) {
        return console.log("本地调试");
      }
      let s = document.querySelector("script");
      let hm = document.createElement("script");
      hm.charset = "UTF-8";
      hm.src = "https://tajs.qq.com/stats?sId=64852535";
      s.parentNode.insertBefore(hm, s);
    })();
  </script>
  <!-- Tencent Analytics End -->



<script src="/js/script.js"></script>

  
  <!-- 尾部用户自定义相关内容 -->

<!-- 插入Sentry -->
<script>
  (function () {
    if (window.location.hostname === "localhost" || window.location.hostname.startsWith("192.168")) {
      return console.log("本地调试");
    }
    let hm = document.createElement("script");
    let s = document.querySelector("script");
    hm.src = "https://browser.sentry-cdn.com/5.10.2/bundle.min.js";
    hm.integrity = "sha384-ssBfXiBvlVC7bdA/VX03S88B5MwXQWdnpJRbUYFPgswlOBwETwTp6F3SMUNpo9M9";
    hm.crossOrigin = "anonymous";
    hm.onload = function () {
      Sentry.init({ dsn: "https://d4e3bac81c30416fb7b917004fdc2a6f@sentry.io/1864685" });
    }
    s.parentNode.insertBefore(hm, s);
  })();
</script>
<!-- 插入Sentry End -->

<!-- 插入百度ESO相关 START -->
<script>
  var _hmt = _hmt || [];
  (function () {
    if (window.location.hostname === "localhost" || window.location.hostname.startsWith("192.168")) {
      return console.log("本地调试");
    }
    var hm = document.createElement("script");
    hm.src = "https://hm.baidu.com/hm.js?410f4beade12e8df64ea4c5622313220";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  });
</script>
<!-- 插入百度ESO相关 END -->

<!-- 插入百度链接自动提交 START -->
<script>
  (function () {
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
      bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
      bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
  })();
</script>
<!-- 插入百度链接自动提交 END --> 
</body>
</html>